// 全局组件Toast（API式）
// 调用简单，无需预渲染，功能扩展较复杂
// 使用方式：直接调用toast.show('消息')或toast.success('成功')

import ReactDOM from "react-dom/client" // 用于将React组件渲染到DOM中

let toastContainer
const toasts = []
let root

function renderToasts() {
    if (!toastContainer) {
        toastContainer = document.createElement("div")
        toastContainer.className = "toast-container"
        document.body.appendChild(toastContainer)
    }
    if (!root) {
        root = ReactDOM.createRoot(toastContainer)
    }

    root.render(
        <>
            {toasts.map((toast, index) => (
                <div key={index} className={`toast ${toast.type}`}>
                    {toast.message}
                </div>
            ))}
        </>
    )
}

export default {
    show: (params) => {
        if (typeof params === "string") {
            toasts.push({ message: params }) // toast.show('消息')
        } else {
            toasts.push({ ...params }) // toast.show({ message: '消息', type: 'success' })
        }

        renderToasts()
        setTimeout(() => {
            toasts.shift() // 移除第一个toast
            renderToasts() // 重新渲染，相当于删除了第一个toast
            if (toasts.length === 0) {
                root.unmount() // 卸载根节点
                document.body.removeChild(toastContainer)
                toastContainer = null
                root = null
            }
        }, params?.duration || 3000)
    },
    success: (message) => this.show(message, { type: "success" }), // toast.success('成功')
    error: (message) => this.show(message, { type: "error" }), // toast.error('失败')
}
